package com.leetcode.algorithm.y22.m07.w4;

import java.util.HashMap;
import java.util.Map;

import com.leetcode.algorithm.common.TreeNode;

/**
 * 105. 从前序与中序遍历序列构造二叉树
 * 
 * https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 * 
 * @author jie.deng
 *
 */
class Question0105Solution02 {

	public TreeNode buildTree(int[] preorder, int[] inorder) {
		int len = preorder.length;
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < inorder.length; i++) {
			map.put(inorder[i], i);
		}
		return buildTree(preorder, 0, inorder, 0, len, map);
	}

	private TreeNode buildTree(int[] preorder, int preLeft, int[] inorder, int inLeft, int len,
			Map<Integer, Integer> map) {
		if (len <= 0) {
			return null;
		}
		int rootNum = preorder[preLeft];
		if (len == 1) {
			return new TreeNode(rootNum);
		}

		TreeNode root = new TreeNode(rootNum);
		int idx = map.get(rootNum);
		int lLen = idx - inLeft;
		int rLen = len - lLen - 1;
		root.left = buildTree(preorder, preLeft + 1, inorder, inLeft, lLen, map);
		root.right = buildTree(preorder, preLeft + 1 + lLen, inorder, idx + 1, rLen, map);
		return root;
	}

}